package zy.service.sqb;

import java.util.Random;

import zy.dto.sqb.PayReq;
import zy.dto.sqb.PayResp;
import zy.dto.sqb.QueryReq;
import zy.util.CommonUtil;
import zy.util.HttpUtil;
import zy.util.MD5;
import zy.util.StringUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class SqbHttpProxy {
	private String api_domain;
    public SqbHttpProxy(String domain){
        api_domain = domain;
    }
    /**
     * 计算字符串的MD5值
     * @param  signStr:签名字符串
     * @return
     */
    public String getSign(String signStr) {
    	try{
            String md5 = MD5.encryptMd5(signStr);
            return md5;
        } catch (Exception e) {
            e.printStackTrace();
            return  null ;
        }
    }
    
    /**
     * 付款
     */
    public PayResp pay(PayReq req){
        String url = api_domain + "/upay/v2/pay";
        JSONObject params = new JSONObject();
        try{
            params.put("terminal_sn",req.getTerminal_sn());
            params.put("client_sn",req.getClient_sn());
            params.put("total_amount",req.getTotal_amount());
            params.put("dynamic_id",req.getDynamic_id());
            params.put("subject",StringUtil.trimString(req.getSubject()));
            params.put("operator",StringUtil.trimString(req.getOperator()));

            String sign = getSign(params.toString() + req.getTerminal_key());
            String result = HttpUtil.httpPost(url, params.toString(),sign,req.getTerminal_sn());
            JSONObject retObj = JSON.parseObject(result);
            String resCode = retObj.get("result_code").toString();
            if(!resCode.equals("200")){
            	return null;
            }
            String responseStr = retObj.get("biz_response").toString();
            JSONObject jsonObject = JSON.parseObject(responseStr);
            PayResp resp = new PayResp();
            JSONObject data = jsonObject.getJSONObject("data");
            resp.setResult_code(jsonObject.getString("result_code"));
            resp.setError_code(jsonObject.getString("error_code"));
            resp.setError_message(jsonObject.getString("error_message"));
            if(data != null){
            	resp.setChannel_finish_time(data.getString("channel_finish_time"));
                resp.setClient_sn(data.getString("client_sn"));
                resp.setClient_tsn(data.getString("client_tsn"));
                resp.setFinish_time(data.getString("finish_time"));
                resp.setNet_amount(data.getString("net_amount"));
                resp.setOperator(data.getString("operator"));
                resp.setOrder_status(data.getString("order_status"));
                resp.setPayer_login(data.getString("payer_login"));
                resp.setPayer_uid(data.getString("payer_uid"));
                resp.setPayment_list(data.getString("payment_list"));
                resp.setPayway(data.getString("payway"));
                resp.setSn(data.getString("sn"));
                resp.setStatus(data.getString("status"));
                resp.setSub_payway(data.getString("sub_payway"));
                resp.setSubject(data.getString("subject"));
                resp.setTotal_amount(data.getString("total_amount"));
                resp.setTrade_no(data.getString("trade_no"));
            }
            return  resp;
        }catch (Exception e){
            return null;
        }
    }
    
    /**
     * 查询
     */
    public PayResp query(QueryReq req){
        String url = api_domain + "/upay/v2/query";
        JSONObject params = new JSONObject();
        try{
            params.put("terminal_sn",req.getTerminal_sn());
            params.put("sn",req.getSn());
            params.put("client_sn",req.getClient_sn());
            String sign = getSign(params.toString() + req.getTerminal_key());
            String result = HttpUtil.httpPost(url, params.toString(),sign,req.getTerminal_sn());
            JSONObject retObj = JSON.parseObject(result);
            String resCode = retObj.get("result_code").toString();
            if(!resCode.equals("200")){
            	return null;
            }
            String responseStr = retObj.get("biz_response").toString();
            JSONObject jsonObject = JSON.parseObject(responseStr);
            PayResp resp = new PayResp();
            JSONObject data = jsonObject.getJSONObject("data");
            resp.setResult_code(jsonObject.getString("result_code"));
            resp.setError_code(jsonObject.getString("error_code"));
            resp.setError_message(jsonObject.getString("error_message"));
			if (data != null) {
				resp.setChannel_finish_time(data.getString("channel_finish_time"));
	            resp.setClient_sn(data.getString("client_sn"));
	            resp.setClient_tsn(data.getString("client_tsn"));
	            resp.setFinish_time(data.getString("finish_time"));
	            resp.setNet_amount(data.getString("net_amount"));
	            resp.setOperator(data.getString("operator"));
	            resp.setOrder_status(data.getString("order_status"));
	            resp.setPayment_list(data.getString("payment_list"));
	            resp.setPayway(data.getString("payway"));
	            resp.setSn(data.getString("sn"));
	            resp.setStatus(data.getString("status"));
	            resp.setSub_payway(data.getString("sub_payway"));
	            resp.setSubject(data.getString("subject"));
	            resp.setTotal_amount(data.getString("total_amount"));
	            resp.setTrade_no(data.getString("trade_no"));
			}
            return  resp;
        }catch (Exception e){
            return null;
        }
    }
    
    /**
     * 仅供测试代码使用
     */
    public static String getClient_Sn(int codeLenth){
        while (true) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < codeLenth; i++) {
                if (i == 0)
                    sb.append(new Random().nextInt(9) + 1); // first field will not start with 0.
                else
                    sb.append(new Random().nextInt(10));
            }
            return sb.toString();
        }
    }
    
    public static void main(String[] args) {
    	SqbHttpProxy httpProxy = new SqbHttpProxy(CommonUtil.SQB_API_DOMAIN);
    	String terminal_sn = "100114020002045886";
		String terminal_key = "0c66bb66dc6d86c498bf5d963a709096";
		
//		PayReq payReq = new PayReq();
//		payReq.setTerminal_sn(terminal_sn);
//		payReq.setTerminal_key(terminal_key);
//		payReq.setClient_sn(getClient_Sn(16));
//		payReq.setMoney(0.01);
//		payReq.setDynamic_id("286918129470851315");//付款码
//		payReq.setSubject("10斤猪肉");
//		payReq.setOperator("张三");
//		PayResp payResp = httpProxy.pay(payReq);
//		System.out.println(JSON.toJSONString(payResp));
		
		QueryReq queryReq = new QueryReq();
		queryReq.setTerminal_sn(terminal_sn);
		queryReq.setTerminal_key(terminal_key);
		queryReq.setClient_sn("2298960752925275");
		queryReq.setSn("7895253594822866");
		PayResp queryResp = httpProxy.query(queryReq);
		System.out.println(JSON.toJSONString(queryResp));
		
	}
    
}
